NamespaceInfo service to replace MWNamespace
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2
3 use MediaWiki\Logger\LegacySpi;
4 use MediaWiki\Logger\LoggerFactory;
5 use MediaWiki\Logger\MonologSpi;
6 use MediaWiki\Logger\LogCapturingSpi;
7 use MediaWiki\MediaWikiServices;
8 use Psr\Log\LoggerInterface;
9 use Wikimedia\Rdbms\IDatabase;
10 use Wikimedia\Rdbms\IMaintainableDatabase;
11 use Wikimedia\Rdbms\Database;
12 use Wikimedia\TestingAccessWrapper;
13
14 /**
15 * @since 1.18
16 */
17 abstract class MediaWikiTestCase extends PHPUnit\Framework\TestCase {
18
19 use MediaWikiCoversValidator;
20 use PHPUnit4And6Compat;
21
22 /**
23 * The original service locator. This is overridden during setUp().
24 *
25 * @var MediaWikiServices|null
26 */
27 private static $originalServices;
28
29 /**
30 * The local service locator, created during setUp().
31 * @var MediaWikiServices
32 */
33 private $localServices;
34
35 /**
36 * $called tracks whether the setUp and tearDown method has been called.
37 * class extending MediaWikiTestCase usually override setUp and tearDown
38 * but forget to call the parent.
39 *
40 * The array format takes a method name as key and anything as a value.
41 * By asserting the key exist, we know the child class has called the
42 * parent.
43 *
44 * This property must be private, we do not want child to override it,
45 * they should call the appropriate parent method instead.
46 */
47 private $called = [];
48
49 /**
50 * @var TestUser[]
51 * @since 1.20
52 */
53 public static $users;
54
55 /**
56 * Primary database
57 *
58 * @var Database
59 * @since 1.18
60 */
61 protected $db;
62
63 /**
64 * @var array
65 * @since 1.19
66 */
67 protected $tablesUsed = []; // tables with data
68
69 private static $useTemporaryTables = true;
70 private static $reuseDB = false;
71 private static $dbSetup = false;
72 private static $oldTablePrefix = '';
73
74 /**
75 * Original value of PHP's error_reporting setting.
76 *
77 * @var int
78 */
79 private $phpErrorLevel;
80
81 /**
82 * Holds the paths of temporary files/directories created through getNewTempFile,
83 * and getNewTempDirectory
84 *
85 * @var array
86 */
87 private $tmpFiles = [];
88
89 /**
90 * Holds original values of MediaWiki configuration settings
91 * to be restored in tearDown().
92 * See also setMwGlobals().
93 * @var array
94 */
95 private $mwGlobals = [];
96
97 /**
98 * Holds list of MediaWiki configuration settings to be unset in tearDown().
99 * See also setMwGlobals().
100 * @var array
101 */
102 private $mwGlobalsToUnset = [];
103
104 /**
105 * Holds original values of ini settings to be restored
106 * in tearDown().
107 * @see setIniSettings()
108 * @var array
109 */
110 private $iniSettings = [];
111
112 /**
113 * Holds original loggers which have been replaced by setLogger()
114 * @var LoggerInterface[]
115 */
116 private $loggers = [];
117
118 /**
119 * The CLI arguments passed through from phpunit.php
120 * @var array
121 */
122 private $cliArgs = [];
123
124 /**
125 * Holds a list of services that were overridden with setService(). Used for printing an error
126 * if overrideMwServices() overrides a service that was previously set.
127 * @var string[]
128 */
129 private $overriddenServices = [];
130
131 /**
132 * Table name prefixes. Oracle likes it shorter.
133 */
134 const DB_PREFIX = 'unittest_';
135 const ORA_DB_PREFIX = 'ut_';
136
137 /**
138 * @var array
139 * @since 1.18
140 */
141 protected $supportedDBs = [
142 'mysql',
143 'sqlite',
144 'postgres',
145 'oracle'
146 ];
147
148 public function __construct( $name = null, array $data = [], $dataName = '' ) {
149 parent::__construct( $name, $data, $dataName );
150
151 $this->backupGlobals = false;
152 $this->backupStaticAttributes = false;
153 }
154
155 public function __destruct() {
156 // Complain if self::setUp() was called, but not self::tearDown()
157 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
158 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
159 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
160 }
161 }
162
163 public static function setUpBeforeClass() {
164 parent::setUpBeforeClass();
165
166 // Get the original service locator
167 if ( !self::$originalServices ) {
168 self::$originalServices = MediaWikiServices::getInstance();
169 }
170 }
171
172 /**
173 * Convenience method for getting an immutable test user
174 *
175 * @since 1.28
176 *
177 * @param string|string[] $groups Groups the test user should be in.
178 * @return TestUser
179 */
180 public static function getTestUser( $groups = [] ) {
181 return TestUserRegistry::getImmutableTestUser( $groups );
182 }
183
184 /**
185 * Convenience method for getting a mutable test user
186 *
187 * @since 1.28
188 *
189 * @param string|string[] $groups Groups the test user should be added in.
190 * @return TestUser
191 */
192 public static function getMutableTestUser( $groups = [] ) {
193 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
194 }
195
196 /**
197 * Convenience method for getting an immutable admin test user
198 *
199 * @since 1.28
200 *
201 * @param string[] $groups Groups the test user should be added to.
202 * @return TestUser
203 */
204 public static function getTestSysop() {
205 return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
206 }
207
208 /**
209 * Returns a WikiPage representing an existing page.
210 *
211 * @since 1.32
212 *
213 * @param Title|string|null $title
214 * @return WikiPage
215 * @throws MWException If this test cases's needsDB() method doesn't return true.
216 * Test cases can use "@group Database" to enable database test support,
217 * or list the tables under testing in $this->tablesUsed, or override the
218 * needsDB() method.
219 */
220 protected function getExistingTestPage( $title = null ) {
221 if ( !$this->needsDB() ) {
222 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
223 ' method should return true. Use @group Database or $this->tablesUsed.' );
224 }
225
226 $title = ( $title === null ) ? 'UTPage' : $title;
227 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
228 $page = WikiPage::factory( $title );
229
230 if ( !$page->exists() ) {
231 $user = self::getTestSysop()->getUser();
232 $page->doEditContent(
233 new WikitextContent( 'UTContent' ),
234 'UTPageSummary',
235 EDIT_NEW | EDIT_SUPPRESS_RC,
236 false,
237 $user
238 );
239 }
240
241 return $page;
242 }
243
244 /**
245 * Returns a WikiPage representing a non-existing page.
246 *
247 * @since 1.32
248 *
249 * @param Title|string|null $title
250 * @return WikiPage
251 * @throws MWException If this test cases's needsDB() method doesn't return true.
252 * Test cases can use "@group Database" to enable database test support,
253 * or list the tables under testing in $this->tablesUsed, or override the
254 * needsDB() method.
255 */
256 protected function getNonexistingTestPage( $title = null ) {
257 if ( !$this->needsDB() ) {
258 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
259 ' method should return true. Use @group Database or $this->tablesUsed.' );
260 }
261
262 $title = ( $title === null ) ? 'UTPage-' . rand( 0, 100000 ) : $title;
263 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
264 $page = WikiPage::factory( $title );
265
266 if ( $page->exists() ) {
267 $page->doDeleteArticle( 'Testing' );
268 }
269
270 return $page;
271 }
272
273 /**
274 * @deprecated since 1.32
275 */
276 public static function prepareServices( Config $bootstrapConfig ) {
277 }
278
279 /**
280 * Create a config suitable for testing, based on a base config, default overrides,
281 * and custom overrides.
282 *
283 * @param Config|null $baseConfig
284 * @param Config|null $customOverrides
285 *
286 * @return Config
287 */
288 private static function makeTestConfig(
289 Config $baseConfig = null,
290 Config $customOverrides = null
291 ) {
292 $defaultOverrides = new HashConfig();
293
294 if ( !$baseConfig ) {
295 $baseConfig = self::$originalServices->getBootstrapConfig();
296 }
297
298 /* Some functions require some kind of caching, and will end up using the db,
299 * which we can't allow, as that would open a new connection for mysql.
300 * Replace with a HashBag. They would not be going to persist anyway.
301 */
302 $hashCache = [ 'class' => HashBagOStuff::class, 'reportDupes' => false ];
303 $objectCaches = [
304 CACHE_DB => $hashCache,
305 CACHE_ACCEL => $hashCache,
306 CACHE_MEMCACHED => $hashCache,
307 'apc' => $hashCache,
308 'apcu' => $hashCache,
309 'wincache' => $hashCache,
310 ] + $baseConfig->get( 'ObjectCaches' );
311
312 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
313 $defaultOverrides->set( 'MainCacheType', CACHE_NONE );
314 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory::class ] ] );
315
316 // Use a fast hash algorithm to hash passwords.
317 $defaultOverrides->set( 'PasswordDefault', 'A' );
318
319 $testConfig = $customOverrides
320 ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
321 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
322
323 return $testConfig;
324 }
325
326 /**
327 * @param ConfigFactory $oldFactory
328 * @param Config[] $configurations
329 *
330 * @return Closure
331 */
332 private static function makeTestConfigFactoryInstantiator(
333 ConfigFactory $oldFactory,
334 array $configurations
335 ) {
336 return function ( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
337 $factory = new ConfigFactory();
338
339 // clone configurations from $oldFactory that are not overwritten by $configurations
340 $namesToClone = array_diff(
341 $oldFactory->getConfigNames(),
342 array_keys( $configurations )
343 );
344
345 foreach ( $namesToClone as $name ) {
346 $factory->register( $name, $oldFactory->makeConfig( $name ) );
347 }
348
349 foreach ( $configurations as $name => $config ) {
350 $factory->register( $name, $config );
351 }
352
353 return $factory;
354 };
355 }
356
357 /**
358 * Resets some non-service singleton instances and other static caches. It's not necessary to
359 * reset services here.
360 */
361 public static function resetNonServiceCaches() {
362 global $wgRequest, $wgJobClasses;
363
364 User::resetGetDefaultOptionsForTestsOnly();
365 foreach ( $wgJobClasses as $type => $class ) {
366 JobQueueGroup::singleton()->get( $type )->delete();
367 }
368 JobQueueGroup::destroySingletons();
369
370 ObjectCache::clear();
371 FileBackendGroup::destroySingleton();
372 DeferredUpdates::clearPendingUpdates();
373
374 // TODO: move global state into MediaWikiServices
375 RequestContext::resetMain();
376 if ( session_id() !== '' ) {
377 session_write_close();
378 session_id( '' );
379 }
380
381 $wgRequest = new FauxRequest();
382 MediaWiki\Session\SessionManager::resetCache();
383 }
384
385 public function run( PHPUnit_Framework_TestResult $result = null ) {
386 if ( $result instanceof MediaWikiTestResult ) {
387 $this->cliArgs = $result->getMediaWikiCliArgs();
388 }
389 $this->overrideMwServices();
390
391 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
392 throw new Exception(
393 get_class( $this ) . ' apparently needsDB but is not in the Database group'
394 );
395 }
396
397 $needsResetDB = false;
398 if ( !self::$dbSetup || $this->needsDB() ) {
399 // set up a DB connection for this test to use
400
401 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
402 self::$reuseDB = $this->getCliArg( 'reuse-db' );
403
404 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
405 $this->db = $lb->getConnection( DB_MASTER );
406
407 $this->checkDbIsSupported();
408
409 if ( !self::$dbSetup ) {
410 $this->setupAllTestDBs();
411 $this->addCoreDBData();
412 }
413
414 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
415 // is available in subclass's setUpBeforeClass() and setUp() methods.
416 // This would also remove the need for the HACK that is oncePerClass().
417 if ( $this->oncePerClass() ) {
418 $this->setUpSchema( $this->db );
419 $this->resetDB( $this->db, $this->tablesUsed );
420 $this->addDBDataOnce();
421 }
422
423 $this->addDBData();
424 $needsResetDB = true;
425 }
426
427 parent::run( $result );
428
429 // We don't mind if we override already-overridden services during cleanup
430 $this->overriddenServices = [];
431
432 if ( $needsResetDB ) {
433 $this->resetDB( $this->db, $this->tablesUsed );
434 }
435
436 self::restoreMwServices();
437 $this->localServices = null;
438 }
439
440 /**
441 * @return bool
442 */
443 private function oncePerClass() {
444 // Remember current test class in the database connection,
445 // so we know when we need to run addData.
446
447 $class = static::class;
448
449 $first = !isset( $this->db->_hasDataForTestClass )
450 || $this->db->_hasDataForTestClass !== $class;
451
452 $this->db->_hasDataForTestClass = $class;
453 return $first;
454 }
455
456 /**
457 * @since 1.21
458 *
459 * @return bool
460 */
461 public function usesTemporaryTables() {
462 return self::$useTemporaryTables;
463 }
464
465 /**
466 * Obtains a new temporary file name
467 *
468 * The obtained filename is enlisted to be removed upon tearDown
469 *
470 * @since 1.20
471 *
472 * @return string Absolute name of the temporary file
473 */
474 protected function getNewTempFile() {
475 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
476 $this->tmpFiles[] = $fileName;
477
478 return $fileName;
479 }
480
481 /**
482 * obtains a new temporary directory
483 *
484 * The obtained directory is enlisted to be removed (recursively with all its contained
485 * files) upon tearDown.
486 *
487 * @since 1.20
488 *
489 * @return string Absolute name of the temporary directory
490 */
491 protected function getNewTempDirectory() {
492 // Starting of with a temporary /file/.
493 $fileName = $this->getNewTempFile();
494
495 // Converting the temporary /file/ to a /directory/
496 // The following is not atomic, but at least we now have a single place,
497 // where temporary directory creation is bundled and can be improved
498 unlink( $fileName );
499 $this->assertTrue( wfMkdirParents( $fileName ) );
500
501 return $fileName;
502 }
503
504 protected function setUp() {
505 parent::setUp();
506 $this->called['setUp'] = true;
507
508 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
509
510 $this->overriddenServices = [];
511
512 // Cleaning up temporary files
513 foreach ( $this->tmpFiles as $fileName ) {
514 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
515 unlink( $fileName );
516 } elseif ( is_dir( $fileName ) ) {
517 wfRecursiveRemoveDir( $fileName );
518 }
519 }
520
521 if ( $this->needsDB() && $this->db ) {
522 // Clean up open transactions
523 while ( $this->db->trxLevel() > 0 ) {
524 $this->db->rollback( __METHOD__, 'flush' );
525 }
526 // Check for unsafe queries
527 if ( $this->db->getType() === 'mysql' ) {
528 $this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__ );
529 }
530 }
531
532 // Reset all caches between tests.
533 self::resetNonServiceCaches();
534
535 // XXX: reset maintenance triggers
536 // Hook into period lag checks which often happen in long-running scripts
537 $lbFactory = $this->localServices->getDBLoadBalancerFactory();
538 Maintenance::setLBFactoryTriggers( $lbFactory, $this->localServices->getMainConfig() );
539
540 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
541 }
542
543 protected function addTmpFiles( $files ) {
544 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
545 }
546
547 // @todo Make const when we no longer support HHVM (T192166)
548 private static $namespaceAffectingSettings = [
549 'wgAllowImageMoving',
550 'wgCanonicalNamespaceNames',
551 'wgCapitalLinkOverrides',
552 'wgCapitalLinks',
553 'wgContentNamespaces',
554 'wgExtensionMessagesFiles',
555 'wgExtensionNamespaces',
556 'wgExtraNamespaces',
557 'wgExtraSignatureNamespaces',
558 'wgNamespaceContentModels',
559 'wgNamespaceProtection',
560 'wgNamespacesWithSubpages',
561 'wgNonincludableNamespaces',
562 'wgRestrictionLevels',
563 ];
564
565 protected function tearDown() {
566 global $wgRequest, $wgSQLMode;
567
568 $status = ob_get_status();
569 if ( isset( $status['name'] ) &&
570 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
571 ) {
572 ob_end_flush();
573 }
574
575 $this->called['tearDown'] = true;
576 // Cleaning up temporary files
577 foreach ( $this->tmpFiles as $fileName ) {
578 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
579 unlink( $fileName );
580 } elseif ( is_dir( $fileName ) ) {
581 wfRecursiveRemoveDir( $fileName );
582 }
583 }
584
585 if ( $this->needsDB() && $this->db ) {
586 // Clean up open transactions
587 while ( $this->db->trxLevel() > 0 ) {
588 $this->db->rollback( __METHOD__, 'flush' );
589 }
590 if ( $this->db->getType() === 'mysql' ) {
591 $this->db->query( "SET sql_mode = " . $this->db->addQuotes( $wgSQLMode ),
592 __METHOD__ );
593 }
594 }
595
596 // Re-enable any disabled deprecation warnings
597 MWDebug::clearLog();
598 // Restore mw globals
599 foreach ( $this->mwGlobals as $key => $value ) {
600 $GLOBALS[$key] = $value;
601 }
602 foreach ( $this->mwGlobalsToUnset as $value ) {
603 unset( $GLOBALS[$value] );
604 }
605 foreach ( $this->iniSettings as $name => $value ) {
606 ini_set( $name, $value );
607 }
608 if (
609 array_intersect( self::$namespaceAffectingSettings, array_keys( $this->mwGlobals ) ) ||
610 array_intersect( self::$namespaceAffectingSettings, $this->mwGlobalsToUnset )
611 ) {
612 $this->resetNamespaces();
613 }
614 $this->mwGlobals = [];
615 $this->mwGlobalsToUnset = [];
616 $this->restoreLoggers();
617
618 // TODO: move global state into MediaWikiServices
619 RequestContext::resetMain();
620 if ( session_id() !== '' ) {
621 session_write_close();
622 session_id( '' );
623 }
624 $wgRequest = new FauxRequest();
625 MediaWiki\Session\SessionManager::resetCache();
626 MediaWiki\Auth\AuthManager::resetCache();
627
628 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
629
630 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
631 ini_set( 'error_reporting', $this->phpErrorLevel );
632
633 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
634 $newHex = strtoupper( dechex( $phpErrorLevel ) );
635 $message = "PHP error_reporting setting was left dirty: "
636 . "was 0x$oldHex before test, 0x$newHex after test!";
637
638 $this->fail( $message );
639 }
640
641 parent::tearDown();
642 }
643
644 /**
645 * Make sure MediaWikiTestCase extending classes have called their
646 * parent setUp method
647 *
648 * With strict coverage activated in PHP_CodeCoverage, this test would be
649 * marked as risky without the following annotation (T152923).
650 * @coversNothing
651 */
652 final public function testMediaWikiTestCaseParentSetupCalled() {
653 $this->assertArrayHasKey( 'setUp', $this->called,
654 static::class . '::setUp() must call parent::setUp()'
655 );
656 }
657
658 /**
659 * Sets a service, maintaining a stashed version of the previous service to be
660 * restored in tearDown
661 *
662 * @since 1.27
663 *
664 * @param string $name
665 * @param object $object
666 */
667 protected function setService( $name, $object ) {
668 if ( !$this->localServices ) {
669 throw new Exception( __METHOD__ . ' must be called after MediaWikiTestCase::run()' );
670 }
671
672 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
673 throw new Exception( __METHOD__ . ' will not work because the global MediaWikiServices '
674 . 'instance has been replaced by test code.' );
675 }
676
677 $this->overriddenServices[] = $name;
678
679 $this->localServices->disableService( $name );
680 $this->localServices->redefineService(
681 $name,
682 function () use ( $object ) {
683 return $object;
684 }
685 );
686
687 if ( $name === 'ContentLanguage' ) {
688 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
689 }
690 }
691
692 /**
693 * Sets a global, maintaining a stashed version of the previous global to be
694 * restored in tearDown
695 *
696 * The key is added to the array of globals that will be reset afterwards
697 * in the tearDown().
698 *
699 * @par Example
700 * @code
701 * protected function setUp() {
702 * $this->setMwGlobals( 'wgRestrictStuff', true );
703 * }
704 *
705 * function testFoo() {}
706 *
707 * function testBar() {}
708 * $this->assertTrue( self::getX()->doStuff() );
709 *
710 * $this->setMwGlobals( 'wgRestrictStuff', false );
711 * $this->assertTrue( self::getX()->doStuff() );
712 * }
713 *
714 * function testQuux() {}
715 * @endcode
716 *
717 * @param array|string $pairs Key to the global variable, or an array
718 * of key/value pairs.
719 * @param mixed|null $value Value to set the global to (ignored
720 * if an array is given as first argument).
721 *
722 * @note To allow changes to global variables to take effect on global service instances,
723 * call overrideMwServices().
724 *
725 * @since 1.21
726 */
727 protected function setMwGlobals( $pairs, $value = null ) {
728 if ( is_string( $pairs ) ) {
729 $pairs = [ $pairs => $value ];
730 }
731
732 if ( isset( $pairs['wgContLang'] ) ) {
733 throw new MWException(
734 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
735 );
736 }
737
738 $this->doSetMwGlobals( $pairs, $value );
739 }
740
741 /**
742 * An internal method that allows setService() to set globals that tests are not supposed to
743 * touch.
744 */
745 private function doSetMwGlobals( $pairs, $value = null ) {
746 $this->doStashMwGlobals( array_keys( $pairs ) );
747
748 foreach ( $pairs as $key => $value ) {
749 $GLOBALS[$key] = $value;
750 }
751
752 if ( array_intersect( self::$namespaceAffectingSettings, array_keys( $pairs ) ) ) {
753 $this->resetNamespaces();
754 }
755 }
756
757 /**
758 * Set an ini setting for the duration of the test
759 * @param string $name Name of the setting
760 * @param string $value Value to set
761 * @since 1.32
762 */
763 protected function setIniSetting( $name, $value ) {
764 $original = ini_get( $name );
765 $this->iniSettings[$name] = $original;
766 ini_set( $name, $value );
767 }
768
769 /**
770 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
771 * Otherwise old namespace data will lurk and cause bugs.
772 */
773 private function resetNamespaces() {
774 if ( !$this->localServices ) {
775 throw new Exception( __METHOD__ . ' must be called after MediaWikiTestCase::run()' );
776 }
777
778 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
779 throw new Exception( __METHOD__ . ' will not work because the global MediaWikiServices '
780 . 'instance has been replaced by test code.' );
781 }
782
783 Language::clearCaches();
784 }
785
786 /**
787 * Check if we can back up a value by performing a shallow copy.
788 * Values which fail this test are copied recursively.
789 *
790 * @param mixed $value
791 * @return bool True if a shallow copy will do; false if a deep copy
792 * is required.
793 */
794 private static function canShallowCopy( $value ) {
795 if ( is_scalar( $value ) || $value === null ) {
796 return true;
797 }
798 if ( is_array( $value ) ) {
799 foreach ( $value as $subValue ) {
800 if ( !is_scalar( $subValue ) && $subValue !== null ) {
801 return false;
802 }
803 }
804 return true;
805 }
806 return false;
807 }
808
809 /**
810 * Stashes the global, will be restored in tearDown()
811 *
812 * Individual test functions may override globals through the setMwGlobals() function
813 * or directly. When directly overriding globals their keys should first be passed to this
814 * method in setUp to avoid breaking global state for other tests
815 *
816 * That way all other tests are executed with the same settings (instead of using the
817 * unreliable local settings for most tests and fix it only for some tests).
818 *
819 * @param array|string $globalKeys Key to the global variable, or an array of keys.
820 *
821 * @note To allow changes to global variables to take effect on global service instances,
822 * call overrideMwServices().
823 *
824 * @since 1.23
825 * @deprecated since 1.32, use setMwGlobals() and don't alter globals directly
826 */
827 protected function stashMwGlobals( $globalKeys ) {
828 wfDeprecated( __METHOD__, '1.32' );
829 $this->doStashMwGlobals( $globalKeys );
830 }
831
832 private function doStashMwGlobals( $globalKeys ) {
833 if ( is_string( $globalKeys ) ) {
834 $globalKeys = [ $globalKeys ];
835 }
836
837 foreach ( $globalKeys as $globalKey ) {
838 // NOTE: make sure we only save the global once or a second call to
839 // setMwGlobals() on the same global would override the original
840 // value.
841 if (
842 !array_key_exists( $globalKey, $this->mwGlobals ) &&
843 !array_key_exists( $globalKey, $this->mwGlobalsToUnset )
844 ) {
845 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
846 $this->mwGlobalsToUnset[$globalKey] = $globalKey;
847 continue;
848 }
849 // NOTE: we serialize then unserialize the value in case it is an object
850 // this stops any objects being passed by reference. We could use clone
851 // and if is_object but this does account for objects within objects!
852 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
853 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
854 } elseif (
855 // Many MediaWiki types are safe to clone. These are the
856 // ones that are most commonly stashed.
857 $GLOBALS[$globalKey] instanceof Language ||
858 $GLOBALS[$globalKey] instanceof User ||
859 $GLOBALS[$globalKey] instanceof FauxRequest
860 ) {
861 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
862 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
863 // Serializing Closure only gives a warning on HHVM while
864 // it throws an Exception on Zend.
865 // Workaround for https://github.com/facebook/hhvm/issues/6206
866 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
867 } else {
868 try {
869 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
870 } catch ( Exception $e ) {
871 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
872 }
873 }
874 }
875 }
876 }
877
878 /**
879 * @param mixed $var
880 * @param int $maxDepth
881 *
882 * @return bool
883 */
884 private function containsClosure( $var, $maxDepth = 15 ) {
885 if ( $var instanceof Closure ) {
886 return true;
887 }
888 if ( !is_array( $var ) || $maxDepth === 0 ) {
889 return false;
890 }
891
892 foreach ( $var as $value ) {
893 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
894 return true;
895 }
896 }
897 return false;
898 }
899
900 /**
901 * Merges the given values into a MW global array variable.
902 * Useful for setting some entries in a configuration array, instead of
903 * setting the entire array.
904 *
905 * @param string $name The name of the global, as in wgFooBar
906 * @param array $values The array containing the entries to set in that global
907 *
908 * @throws MWException If the designated global is not an array.
909 *
910 * @note To allow changes to global variables to take effect on global service instances,
911 * call overrideMwServices().
912 *
913 * @since 1.21
914 */
915 protected function mergeMwGlobalArrayValue( $name, $values ) {
916 if ( !isset( $GLOBALS[$name] ) ) {
917 $merged = $values;
918 } else {
919 if ( !is_array( $GLOBALS[$name] ) ) {
920 throw new MWException( "MW global $name is not an array." );
921 }
922
923 // NOTE: do not use array_merge, it screws up for numeric keys.
924 $merged = $GLOBALS[$name];
925 foreach ( $values as $k => $v ) {
926 $merged[$k] = $v;
927 }
928 }
929
930 $this->setMwGlobals( $name, $merged );
931 }
932
933 /**
934 * Stashes the global instance of MediaWikiServices, and installs a new one,
935 * allowing test cases to override settings and services.
936 * The previous instance of MediaWikiServices will be restored on tearDown.
937 *
938 * @since 1.27
939 *
940 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
941 * instance.
942 * @param callable[] $services An associative array of services to re-define. Keys are service
943 * names, values are callables.
944 *
945 * @return MediaWikiServices
946 * @throws MWException
947 */
948 protected function overrideMwServices(
949 Config $configOverrides = null, array $services = []
950 ) {
951 if ( $this->overriddenServices ) {
952 throw new MWException(
953 'The following services were set and are now being unset by overrideMwServices: ' .
954 implode( ', ', $this->overriddenServices )
955 );
956 }
957 $newInstance = self::installMockMwServices( $configOverrides );
958
959 if ( $this->localServices ) {
960 $this->localServices->destroy();
961 }
962
963 $this->localServices = $newInstance;
964
965 foreach ( $services as $name => $callback ) {
966 $newInstance->redefineService( $name, $callback );
967 }
968
969 return $newInstance;
970 }
971
972 /**
973 * Creates a new "mock" MediaWikiServices instance, and installs it.
974 * This effectively resets all cached states in services, with the exception of
975 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
976 * the original MediaWikiServices.
977 *
978 * @note The new original MediaWikiServices instance can later be restored by calling
979 * restoreMwServices(). That original is determined by the first call to this method, or
980 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
981 * and, when appropriate, destroying any other MediaWikiServices instances that may get
982 * replaced when calling this method.
983 *
984 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
985 * instance.
986 *
987 * @return MediaWikiServices the new mock service locator.
988 */
989 public static function installMockMwServices( Config $configOverrides = null ) {
990 // Make sure we have the original service locator
991 if ( !self::$originalServices ) {
992 self::$originalServices = MediaWikiServices::getInstance();
993 }
994
995 if ( !$configOverrides ) {
996 $configOverrides = new HashConfig();
997 }
998
999 $oldConfigFactory = self::$originalServices->getConfigFactory();
1000 $oldLoadBalancerFactory = self::$originalServices->getDBLoadBalancerFactory();
1001
1002 $testConfig = self::makeTestConfig( null, $configOverrides );
1003 $newServices = new MediaWikiServices( $testConfig );
1004
1005 // Load the default wiring from the specified files.
1006 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1007 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1008 $newServices->loadWiringFiles( $wiringFiles );
1009
1010 // Provide a traditional hook point to allow extensions to configure services.
1011 Hooks::run( 'MediaWikiServices', [ $newServices ] );
1012
1013 // Use bootstrap config for all configuration.
1014 // This allows config overrides via global variables to take effect.
1015 $bootstrapConfig = $newServices->getBootstrapConfig();
1016 $newServices->resetServiceForTesting( 'ConfigFactory' );
1017 $newServices->redefineService(
1018 'ConfigFactory',
1019 self::makeTestConfigFactoryInstantiator(
1020 $oldConfigFactory,
1021 [ 'main' => $bootstrapConfig ]
1022 )
1023 );
1024 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1025 $newServices->redefineService(
1026 'DBLoadBalancerFactory',
1027 function ( MediaWikiServices $services ) use ( $oldLoadBalancerFactory ) {
1028 return $oldLoadBalancerFactory;
1029 }
1030 );
1031
1032 MediaWikiServices::forceGlobalInstance( $newServices );
1033 return $newServices;
1034 }
1035
1036 /**
1037 * Restores the original, non-mock MediaWikiServices instance.
1038 * The previously active MediaWikiServices instance is destroyed,
1039 * if it is different from the original that is to be restored.
1040 *
1041 * @note this if for internal use by test framework code. It should never be
1042 * called from inside a test case, a data provider, or a setUp or tearDown method.
1043 *
1044 * @return bool true if the original service locator was restored,
1045 * false if there was nothing too do.
1046 */
1047 public static function restoreMwServices() {
1048 if ( !self::$originalServices ) {
1049 return false;
1050 }
1051
1052 $currentServices = MediaWikiServices::getInstance();
1053
1054 if ( self::$originalServices === $currentServices ) {
1055 return false;
1056 }
1057
1058 MediaWikiServices::forceGlobalInstance( self::$originalServices );
1059 $currentServices->destroy();
1060
1061 return true;
1062 }
1063
1064 /**
1065 * @since 1.27
1066 * @param string|Language $lang
1067 */
1068 public function setUserLang( $lang ) {
1069 RequestContext::getMain()->setLanguage( $lang );
1070 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
1071 }
1072
1073 /**
1074 * @since 1.27
1075 * @param string|Language $lang
1076 */
1077 public function setContentLang( $lang ) {
1078 if ( $lang instanceof Language ) {
1079 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1080 // Set to the exact object requested
1081 $this->setService( 'ContentLanguage', $lang );
1082 } else {
1083 $this->setMwGlobals( 'wgLanguageCode', $lang );
1084 // Let the service handler make up the object. Avoid calling setService(), because if
1085 // we do, overrideMwServices() will complain if it's called later on.
1086 $services = MediaWikiServices::getInstance();
1087 $services->resetServiceForTesting( 'ContentLanguage' );
1088 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1089 }
1090 }
1091
1092 /**
1093 * Alters $wgGroupPermissions for the duration of the test. Can be called
1094 * with an array, like
1095 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1096 * or three values to set a single permission, like
1097 * $this->setGroupPermissions( '*', 'read', false );
1098 *
1099 * @since 1.31
1100 * @param array|string $newPerms Either an array of permissions to change,
1101 * in which case the next two parameters are ignored; or a single string
1102 * identifying a group, to use with the next two parameters.
1103 * @param string|null $newKey
1104 * @param mixed|null $newValue
1105 */
1106 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1107 global $wgGroupPermissions;
1108
1109 if ( is_string( $newPerms ) ) {
1110 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1111 }
1112
1113 $newPermissions = $wgGroupPermissions;
1114 foreach ( $newPerms as $group => $permissions ) {
1115 foreach ( $permissions as $key => $value ) {
1116 $newPermissions[$group][$key] = $value;
1117 }
1118 }
1119
1120 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1121 }
1122
1123 /**
1124 * Sets the logger for a specified channel, for the duration of the test.
1125 * @since 1.27
1126 * @param string $channel
1127 * @param LoggerInterface $logger
1128 */
1129 protected function setLogger( $channel, LoggerInterface $logger ) {
1130 // TODO: Once loggers are managed by MediaWikiServices, use
1131 // overrideMwServices() to set loggers.
1132
1133 $provider = LoggerFactory::getProvider();
1134 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1135 $singletons = $wrappedProvider->singletons;
1136 if ( $provider instanceof MonologSpi ) {
1137 if ( !isset( $this->loggers[$channel] ) ) {
1138 $this->loggers[$channel] = $singletons['loggers'][$channel] ?? null;
1139 }
1140 $singletons['loggers'][$channel] = $logger;
1141 } elseif ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1142 if ( !isset( $this->loggers[$channel] ) ) {
1143 $this->loggers[$channel] = $singletons[$channel] ?? null;
1144 }
1145 $singletons[$channel] = $logger;
1146 } else {
1147 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
1148 . ' is not implemented' );
1149 }
1150 $wrappedProvider->singletons = $singletons;
1151 }
1152
1153 /**
1154 * Restores loggers replaced by setLogger().
1155 * @since 1.27
1156 */
1157 private function restoreLoggers() {
1158 $provider = LoggerFactory::getProvider();
1159 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1160 $singletons = $wrappedProvider->singletons;
1161 foreach ( $this->loggers as $channel => $logger ) {
1162 if ( $provider instanceof MonologSpi ) {
1163 if ( $logger === null ) {
1164 unset( $singletons['loggers'][$channel] );
1165 } else {
1166 $singletons['loggers'][$channel] = $logger;
1167 }
1168 } elseif ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1169 if ( $logger === null ) {
1170 unset( $singletons[$channel] );
1171 } else {
1172 $singletons[$channel] = $logger;
1173 }
1174 }
1175 }
1176 $wrappedProvider->singletons = $singletons;
1177 $this->loggers = [];
1178 }
1179
1180 /**
1181 * @return string
1182 * @since 1.18
1183 */
1184 public function dbPrefix() {
1185 return self::getTestPrefixFor( $this->db );
1186 }
1187
1188 /**
1189 * @param IDatabase $db
1190 * @return string
1191 * @since 1.32
1192 */
1193 public static function getTestPrefixFor( IDatabase $db ) {
1194 return $db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
1195 }
1196
1197 /**
1198 * @return bool
1199 * @since 1.18
1200 */
1201 public function needsDB() {
1202 // If the test says it uses database tables, it needs the database
1203 return $this->tablesUsed || $this->isTestInDatabaseGroup();
1204 }
1205
1206 /**
1207 * @return bool
1208 * @since 1.32
1209 */
1210 protected function isTestInDatabaseGroup() {
1211 // If the test class says it belongs to the Database group, it needs the database.
1212 // NOTE: This ONLY checks for the group in the class level doc comment.
1213 $rc = new ReflectionClass( $this );
1214 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1215 }
1216
1217 /**
1218 * Insert a new page.
1219 *
1220 * Should be called from addDBData().
1221 *
1222 * @since 1.25 ($namespace in 1.28)
1223 * @param string|Title $pageName Page name or title
1224 * @param string $text Page's content
1225 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1226 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1227 * @return array Title object and page id
1228 * @throws MWException If this test cases's needsDB() method doesn't return true.
1229 * Test cases can use "@group Database" to enable database test support,
1230 * or list the tables under testing in $this->tablesUsed, or override the
1231 * needsDB() method.
1232 */
1233 protected function insertPage(
1234 $pageName,
1235 $text = 'Sample page for unit test.',
1236 $namespace = null,
1237 User $user = null
1238 ) {
1239 if ( !$this->needsDB() ) {
1240 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1241 ' method should return true. Use @group Database or $this->tablesUsed.' );
1242 }
1243
1244 if ( is_string( $pageName ) ) {
1245 $title = Title::newFromText( $pageName, $namespace );
1246 } else {
1247 $title = $pageName;
1248 }
1249
1250 if ( !$user ) {
1251 $user = static::getTestSysop()->getUser();
1252 }
1253 $comment = __METHOD__ . ': Sample page for unit test.';
1254
1255 $page = WikiPage::factory( $title );
1256 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
1257
1258 return [
1259 'title' => $title,
1260 'id' => $page->getId(),
1261 ];
1262 }
1263
1264 /**
1265 * Stub. If a test suite needs to add additional data to the database, it should
1266 * implement this method and do so. This method is called once per test suite
1267 * (i.e. once per class).
1268 *
1269 * Note data added by this method may be removed by resetDB() depending on
1270 * the contents of $tablesUsed.
1271 *
1272 * To add additional data between test function runs, override prepareDB().
1273 *
1274 * @see addDBData()
1275 * @see resetDB()
1276 *
1277 * @since 1.27
1278 */
1279 public function addDBDataOnce() {
1280 }
1281
1282 /**
1283 * Stub. Subclasses may override this to prepare the database.
1284 * Called before every test run (test function or data set).
1285 *
1286 * @see addDBDataOnce()
1287 * @see resetDB()
1288 *
1289 * @since 1.18
1290 */
1291 public function addDBData() {
1292 }
1293
1294 /**
1295 * @since 1.32
1296 */
1297 protected function addCoreDBData() {
1298 if ( $this->db->getType() == 'oracle' ) {
1299 # Insert 0 user to prevent FK violations
1300 # Anonymous user
1301 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1302 $this->db->insert( 'user', [
1303 'user_id' => 0,
1304 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
1305 }
1306
1307 # Insert 0 page to prevent FK violations
1308 # Blank page
1309 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1310 $this->db->insert( 'page', [
1311 'page_id' => 0,
1312 'page_namespace' => 0,
1313 'page_title' => ' ',
1314 'page_restrictions' => null,
1315 'page_is_redirect' => 0,
1316 'page_is_new' => 0,
1317 'page_random' => 0,
1318 'page_touched' => $this->db->timestamp(),
1319 'page_latest' => 0,
1320 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
1321 }
1322 }
1323
1324 SiteStatsInit::doPlaceholderInit();
1325
1326 User::resetIdByNameCache();
1327
1328 // Make sysop user
1329 $user = static::getTestSysop()->getUser();
1330
1331 // Make 1 page with 1 revision
1332 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1333 if ( $page->getId() == 0 ) {
1334 $page->doEditContent(
1335 new WikitextContent( 'UTContent' ),
1336 'UTPageSummary',
1337 EDIT_NEW | EDIT_SUPPRESS_RC,
1338 false,
1339 $user
1340 );
1341 // an edit always attempt to purge backlink links such as history
1342 // pages. That is unnecessary.
1343 JobQueueGroup::singleton()->get( 'htmlCacheUpdate' )->delete();
1344 // WikiPages::doEditUpdates randomly adds RC purges
1345 JobQueueGroup::singleton()->get( 'recentChangesUpdate' )->delete();
1346
1347 // doEditContent() probably started the session via
1348 // User::loadFromSession(). Close it now.
1349 if ( session_id() !== '' ) {
1350 session_write_close();
1351 session_id( '' );
1352 }
1353 }
1354 }
1355
1356 /**
1357 * Restores MediaWiki to using the table set (table prefix) it was using before
1358 * setupTestDB() was called. Useful if we need to perform database operations
1359 * after the test run has finished (such as saving logs or profiling info).
1360 *
1361 * This is called by phpunit/bootstrap.php after the last test.
1362 *
1363 * @since 1.21
1364 */
1365 public static function teardownTestDB() {
1366 global $wgJobClasses;
1367
1368 if ( !self::$dbSetup ) {
1369 return;
1370 }
1371
1372 Hooks::run( 'UnitTestsBeforeDatabaseTeardown' );
1373
1374 foreach ( $wgJobClasses as $type => $class ) {
1375 // Delete any jobs under the clone DB (or old prefix in other stores)
1376 JobQueueGroup::singleton()->get( $type )->delete();
1377 }
1378
1379 // T219673: close any connections from code that failed to call reuseConnection()
1380 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1381 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->closeAll();
1382 CloneDatabase::changePrefix( self::$oldTablePrefix );
1383
1384 self::$oldTablePrefix = false;
1385 self::$dbSetup = false;
1386 }
1387
1388 /**
1389 * Setups a database with cloned tables using the given prefix.
1390 *
1391 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1392 * Otherwise, it will clone the tables and change the prefix.
1393 *
1394 * @param IMaintainableDatabase $db Database to use
1395 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1396 * automatically for $db.
1397 * @return bool True if tables were cloned, false if only the prefix was changed
1398 */
1399 protected static function setupDatabaseWithTestPrefix(
1400 IMaintainableDatabase $db,
1401 $prefix = null
1402 ) {
1403 if ( $prefix === null ) {
1404 $prefix = self::getTestPrefixFor( $db );
1405 }
1406
1407 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1408 $db->tablePrefix( $prefix );
1409 return false;
1410 }
1411
1412 if ( !isset( $db->_originalTablePrefix ) ) {
1413 $oldPrefix = $db->tablePrefix();
1414
1415 if ( $oldPrefix === $prefix ) {
1416 // table already has the correct prefix, but presumably no cloned tables
1417 $oldPrefix = self::$oldTablePrefix;
1418 }
1419
1420 $db->tablePrefix( $oldPrefix );
1421 $tablesCloned = self::listTables( $db );
1422 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1423 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1424
1425 $dbClone->cloneTableStructure();
1426
1427 $db->tablePrefix( $prefix );
1428 $db->_originalTablePrefix = $oldPrefix;
1429 }
1430
1431 return true;
1432 }
1433
1434 /**
1435 * Set up all test DBs
1436 */
1437 public function setupAllTestDBs() {
1438 global $wgDBprefix;
1439
1440 self::$oldTablePrefix = $wgDBprefix;
1441
1442 $testPrefix = $this->dbPrefix();
1443
1444 // switch to a temporary clone of the database
1445 self::setupTestDB( $this->db, $testPrefix );
1446
1447 if ( self::isUsingExternalStoreDB() ) {
1448 self::setupExternalStoreTestDBs( $testPrefix );
1449 }
1450
1451 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1452 // *any* database connections to operate on live data.
1453 CloneDatabase::changePrefix( $testPrefix );
1454 }
1455
1456 /**
1457 * Creates an empty skeleton of the wiki database by cloning its structure
1458 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1459 * use the new set of tables (aka schema) instead of the original set.
1460 *
1461 * This is used to generate a dummy table set, typically consisting of temporary
1462 * tables, that will be used by tests instead of the original wiki database tables.
1463 *
1464 * @since 1.21
1465 *
1466 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1467 * by teardownTestDB() to return the wiki to using the original table set.
1468 *
1469 * @note this method only works when first called. Subsequent calls have no effect,
1470 * even if using different parameters.
1471 *
1472 * @param IMaintainableDatabase $db The database connection
1473 * @param string $prefix The prefix to use for the new table set (aka schema).
1474 *
1475 * @throws MWException If the database table prefix is already $prefix
1476 */
1477 public static function setupTestDB( IMaintainableDatabase $db, $prefix ) {
1478 if ( self::$dbSetup ) {
1479 return;
1480 }
1481
1482 if ( $db->tablePrefix() === $prefix ) {
1483 throw new MWException(
1484 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1485 }
1486
1487 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1488 // and Database no longer use global state.
1489
1490 self::$dbSetup = true;
1491
1492 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1493 return;
1494 }
1495
1496 // Assuming this isn't needed for External Store database, and not sure if the procedure
1497 // would be available there.
1498 if ( $db->getType() == 'oracle' ) {
1499 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__ );
1500 }
1501
1502 Hooks::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1503 }
1504
1505 /**
1506 * Clones the External Store database(s) for testing
1507 *
1508 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1509 * if not given.
1510 */
1511 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1512 $connections = self::getExternalStoreDatabaseConnections();
1513 foreach ( $connections as $dbw ) {
1514 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1515 }
1516 }
1517
1518 /**
1519 * Gets master database connections for all of the ExternalStoreDB
1520 * stores configured in $wgDefaultExternalStore.
1521 *
1522 * @return Database[] Array of Database master connections
1523 */
1524 protected static function getExternalStoreDatabaseConnections() {
1525 global $wgDefaultExternalStore;
1526
1527 /** @var ExternalStoreDB $externalStoreDB */
1528 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1529 $defaultArray = (array)$wgDefaultExternalStore;
1530 $dbws = [];
1531 foreach ( $defaultArray as $url ) {
1532 if ( strpos( $url, 'DB://' ) === 0 ) {
1533 list( $proto, $cluster ) = explode( '://', $url, 2 );
1534 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1535 // requires Database instead of plain DBConnRef/IDatabase
1536 $dbws[] = $externalStoreDB->getMaster( $cluster );
1537 }
1538 }
1539
1540 return $dbws;
1541 }
1542
1543 /**
1544 * Check whether ExternalStoreDB is being used
1545 *
1546 * @return bool True if it's being used
1547 */
1548 protected static function isUsingExternalStoreDB() {
1549 global $wgDefaultExternalStore;
1550 if ( !$wgDefaultExternalStore ) {
1551 return false;
1552 }
1553
1554 $defaultArray = (array)$wgDefaultExternalStore;
1555 foreach ( $defaultArray as $url ) {
1556 if ( strpos( $url, 'DB://' ) === 0 ) {
1557 return true;
1558 }
1559 }
1560
1561 return false;
1562 }
1563
1564 /**
1565 * @throws LogicException if the given database connection is not a set up to use
1566 * mock tables.
1567 *
1568 * @since 1.31 this is no longer private.
1569 */
1570 protected function ensureMockDatabaseConnection( IDatabase $db ) {
1571 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1572 throw new LogicException(
1573 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1574 );
1575 }
1576 }
1577
1578 private static $schemaOverrideDefaults = [
1579 'scripts' => [],
1580 'create' => [],
1581 'drop' => [],
1582 'alter' => [],
1583 ];
1584
1585 /**
1586 * Stub. If a test suite needs to test against a specific database schema, it should
1587 * override this method and return the appropriate information from it.
1588 *
1589 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1590 * May be used to check the current state of the schema, to determine what
1591 * overrides are needed.
1592 *
1593 * @return array An associative array with the following fields:
1594 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1595 * - 'create': A list of tables created (may or may not exist in the original schema).
1596 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1597 * - 'alter': A list of tables altered (expected to be present in the original schema).
1598 */
1599 protected function getSchemaOverrides( IMaintainableDatabase $db ) {
1600 return [];
1601 }
1602
1603 /**
1604 * Undoes the specified schema overrides..
1605 * Called once per test class, just before addDataOnce().
1606 *
1607 * @param IMaintainableDatabase $db
1608 * @param array $oldOverrides
1609 */
1610 private function undoSchemaOverrides( IMaintainableDatabase $db, $oldOverrides ) {
1611 $this->ensureMockDatabaseConnection( $db );
1612
1613 $oldOverrides = $oldOverrides + self::$schemaOverrideDefaults;
1614 $originalTables = $this->listOriginalTables( $db );
1615
1616 // Drop tables that need to be restored or removed.
1617 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1618
1619 // Restore tables that have been dropped or created or altered,
1620 // if they exist in the original schema.
1621 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1622 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1623
1624 if ( $tablesToDrop ) {
1625 $this->dropMockTables( $db, $tablesToDrop );
1626 }
1627
1628 if ( $tablesToRestore ) {
1629 $this->recloneMockTables( $db, $tablesToRestore );
1630 }
1631 }
1632
1633 /**
1634 * Applies the schema overrides returned by getSchemaOverrides(),
1635 * after undoing any previously applied schema overrides.
1636 * Called once per test class, just before addDataOnce().
1637 */
1638 private function setUpSchema( IMaintainableDatabase $db ) {
1639 // Undo any active overrides.
1640 $oldOverrides = $db->_schemaOverrides ?? self::$schemaOverrideDefaults;
1641
1642 if ( $oldOverrides['alter'] || $oldOverrides['create'] || $oldOverrides['drop'] ) {
1643 $this->undoSchemaOverrides( $db, $oldOverrides );
1644 }
1645
1646 // Determine new overrides.
1647 $overrides = $this->getSchemaOverrides( $db ) + self::$schemaOverrideDefaults;
1648
1649 $extraKeys = array_diff(
1650 array_keys( $overrides ),
1651 array_keys( self::$schemaOverrideDefaults )
1652 );
1653
1654 if ( $extraKeys ) {
1655 throw new InvalidArgumentException(
1656 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1657 );
1658 }
1659
1660 if ( !$overrides['scripts'] ) {
1661 // no scripts to run
1662 return;
1663 }
1664
1665 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1666 throw new InvalidArgumentException(
1667 'Schema override scripts given, but no tables are declared to be '
1668 . 'created, dropped or altered.'
1669 );
1670 }
1671
1672 $this->ensureMockDatabaseConnection( $db );
1673
1674 // Drop the tables that will be created by the schema scripts.
1675 $originalTables = $this->listOriginalTables( $db );
1676 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1677
1678 if ( $tablesToDrop ) {
1679 $this->dropMockTables( $db, $tablesToDrop );
1680 }
1681
1682 // Run schema override scripts.
1683 foreach ( $overrides['scripts'] as $script ) {
1684 $db->sourceFile(
1685 $script,
1686 null,
1687 null,
1688 __METHOD__,
1689 function ( $cmd ) {
1690 return $this->mungeSchemaUpdateQuery( $cmd );
1691 }
1692 );
1693 }
1694
1695 $db->_schemaOverrides = $overrides;
1696 }
1697
1698 private function mungeSchemaUpdateQuery( $cmd ) {
1699 return self::$useTemporaryTables
1700 ? preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1701 : $cmd;
1702 }
1703
1704 /**
1705 * Drops the given mock tables.
1706 *
1707 * @param IMaintainableDatabase $db
1708 * @param array $tables
1709 */
1710 private function dropMockTables( IMaintainableDatabase $db, array $tables ) {
1711 $this->ensureMockDatabaseConnection( $db );
1712
1713 foreach ( $tables as $tbl ) {
1714 $tbl = $db->tableName( $tbl );
1715 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__ );
1716 }
1717 }
1718
1719 /**
1720 * Lists all tables in the live database schema, without a prefix.
1721 *
1722 * @param IMaintainableDatabase $db
1723 * @return array
1724 */
1725 private function listOriginalTables( IMaintainableDatabase $db ) {
1726 if ( !isset( $db->_originalTablePrefix ) ) {
1727 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1728 }
1729
1730 $originalTables = $db->listTables( $db->_originalTablePrefix, __METHOD__ );
1731
1732 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1733 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix, '/' ) . '/';
1734
1735 $originalTables = array_filter(
1736 $originalTables,
1737 function ( $pt ) use ( $unittestPrefixRegex ) {
1738 return !preg_match( $unittestPrefixRegex, $pt );
1739 }
1740 );
1741
1742 $originalTables = array_map(
1743 function ( $pt ) use ( $originalPrefixRegex ) {
1744 return preg_replace( $originalPrefixRegex, '', $pt );
1745 },
1746 $originalTables
1747 );
1748
1749 return array_unique( $originalTables );
1750 }
1751
1752 /**
1753 * Re-clones the given mock tables to restore them based on the live database schema.
1754 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1755 * should be called first.
1756 *
1757 * @param IMaintainableDatabase $db
1758 * @param array $tables
1759 */
1760 private function recloneMockTables( IMaintainableDatabase $db, array $tables ) {
1761 $this->ensureMockDatabaseConnection( $db );
1762
1763 if ( !isset( $db->_originalTablePrefix ) ) {
1764 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1765 }
1766
1767 $originalTables = $this->listOriginalTables( $db );
1768 $tables = array_intersect( $tables, $originalTables );
1769
1770 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix );
1771 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1772
1773 $dbClone->cloneTableStructure();
1774 }
1775
1776 /**
1777 * Empty all tables so they can be repopulated for tests
1778 *
1779 * @param Database $db|null Database to reset
1780 * @param array $tablesUsed Tables to reset
1781 */
1782 private function resetDB( $db, $tablesUsed ) {
1783 if ( $db ) {
1784 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1785 $pageTables = [
1786 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1787 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1788 ];
1789 $coreDBDataTables = array_merge( $userTables, $pageTables );
1790
1791 // If any of the user or page tables were marked as used, we should clear all of them.
1792 if ( array_intersect( $tablesUsed, $userTables ) ) {
1793 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1794 TestUserRegistry::clear();
1795 }
1796 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1797 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1798 }
1799
1800 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1801 // instead of user/text. But Postgres does not remap the
1802 // table name in tableExists(), so we mark the real table
1803 // names as being used.
1804 if ( $db->getType() === 'postgres' ) {
1805 if ( in_array( 'user', $tablesUsed ) ) {
1806 $tablesUsed[] = 'mwuser';
1807 }
1808 if ( in_array( 'text', $tablesUsed ) ) {
1809 $tablesUsed[] = 'pagecontent';
1810 }
1811 }
1812
1813 foreach ( $tablesUsed as $tbl ) {
1814 $this->truncateTable( $tbl, $db );
1815 }
1816
1817 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1818 // Reset services that may contain information relating to the truncated tables
1819 $this->overrideMwServices();
1820 // Re-add core DB data that was deleted
1821 $this->addCoreDBData();
1822 }
1823 }
1824 }
1825
1826 /**
1827 * Empties the given table and resets any auto-increment counters.
1828 * Will also purge caches associated with some well known tables.
1829 * If the table is not know, this method just returns.
1830 *
1831 * @param string $tableName
1832 * @param IDatabase|null $db
1833 */
1834 protected function truncateTable( $tableName, IDatabase $db = null ) {
1835 if ( !$db ) {
1836 $db = $this->db;
1837 }
1838
1839 if ( !$db->tableExists( $tableName ) ) {
1840 return;
1841 }
1842
1843 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1844
1845 if ( $truncate ) {
1846 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__ );
1847 } else {
1848 $db->delete( $tableName, '*', __METHOD__ );
1849 }
1850
1851 if ( $db instanceof DatabasePostgres || $db instanceof DatabaseSqlite ) {
1852 // Reset the table's sequence too.
1853 $db->resetSequenceForTable( $tableName, __METHOD__ );
1854 }
1855
1856 // re-initialize site_stats table
1857 if ( $tableName === 'site_stats' ) {
1858 SiteStatsInit::doPlaceholderInit();
1859 }
1860 }
1861
1862 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1863 $tableName = substr( $tableName, strlen( $prefix ) );
1864 }
1865
1866 private static function isNotUnittest( $table ) {
1867 return strpos( $table, self::DB_PREFIX ) !== 0;
1868 }
1869
1870 /**
1871 * @since 1.18
1872 *
1873 * @param IMaintainableDatabase $db
1874 *
1875 * @return array
1876 */
1877 public static function listTables( IMaintainableDatabase $db ) {
1878 $prefix = $db->tablePrefix();
1879 $tables = $db->listTables( $prefix, __METHOD__ );
1880
1881 if ( $db->getType() === 'mysql' ) {
1882 static $viewListCache = null;
1883 if ( $viewListCache === null ) {
1884 $viewListCache = $db->listViews( null, __METHOD__ );
1885 }
1886 // T45571: cannot clone VIEWs under MySQL
1887 $tables = array_diff( $tables, $viewListCache );
1888 }
1889 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1890
1891 // Don't duplicate test tables from the previous fataled run
1892 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1893
1894 if ( $db->getType() == 'sqlite' ) {
1895 $tables = array_flip( $tables );
1896 // these are subtables of searchindex and don't need to be duped/dropped separately
1897 unset( $tables['searchindex_content'] );
1898 unset( $tables['searchindex_segdir'] );
1899 unset( $tables['searchindex_segments'] );
1900 $tables = array_flip( $tables );
1901 }
1902
1903 return $tables;
1904 }
1905
1906 /**
1907 * Copy test data from one database connection to another.
1908 *
1909 * This should only be used for small data sets.
1910 *
1911 * @param IDatabase $source
1912 * @param IDatabase $target
1913 */
1914 public function copyTestData( IDatabase $source, IDatabase $target ) {
1915 if ( $this->db->getType() === 'sqlite' ) {
1916 // SQLite uses a non-temporary copy of the searchindex table for testing,
1917 // which gets deleted and re-created when setting up the secondary connection,
1918 // causing "Error 17" when trying to copy the data. See T191863#4130112.
1919 throw new RuntimeException(
1920 'Setting up a secondary database connection with test data is currently not'
1921 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
1922 );
1923 }
1924
1925 $tables = self::listOriginalTables( $source );
1926
1927 foreach ( $tables as $table ) {
1928 $res = $source->select( $table, '*', [], __METHOD__ );
1929 $allRows = [];
1930
1931 foreach ( $res as $row ) {
1932 $allRows[] = (array)$row;
1933 }
1934
1935 $target->insert( $table, $allRows, __METHOD__, [ 'IGNORE' ] );
1936 }
1937 }
1938
1939 /**
1940 * @throws MWException
1941 * @since 1.18
1942 */
1943 protected function checkDbIsSupported() {
1944 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1945 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1946 }
1947 }
1948
1949 /**
1950 * @since 1.18
1951 * @param string $offset
1952 * @return mixed
1953 */
1954 public function getCliArg( $offset ) {
1955 return $this->cliArgs[$offset] ?? null;
1956 }
1957
1958 /**
1959 * @since 1.18
1960 * @param string $offset
1961 * @param mixed $value
1962 */
1963 public function setCliArg( $offset, $value ) {
1964 $this->cliArgs[$offset] = $value;
1965 }
1966
1967 /**
1968 * Don't throw a warning if $function is deprecated and called later
1969 *
1970 * @since 1.19
1971 *
1972 * @param string $function
1973 */
1974 public function hideDeprecated( $function ) {
1975 Wikimedia\suppressWarnings();
1976 wfDeprecated( $function );
1977 Wikimedia\restoreWarnings();
1978 }
1979
1980 /**
1981 * Asserts that the given database query yields the rows given by $expectedRows.
1982 * The expected rows should be given as indexed (not associative) arrays, with
1983 * the values given in the order of the columns in the $fields parameter.
1984 * Note that the rows are sorted by the columns given in $fields.
1985 *
1986 * @since 1.20
1987 *
1988 * @param string|array $table The table(s) to query
1989 * @param string|array $fields The columns to include in the result (and to sort by)
1990 * @param string|array $condition "where" condition(s)
1991 * @param array $expectedRows An array of arrays giving the expected rows.
1992 * @param array $options Options for the query
1993 * @param array $join_conds Join conditions for the query
1994 *
1995 * @throws MWException If this test cases's needsDB() method doesn't return true.
1996 * Test cases can use "@group Database" to enable database test support,
1997 * or list the tables under testing in $this->tablesUsed, or override the
1998 * needsDB() method.
1999 */
2000 protected function assertSelect(
2001 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2002 ) {
2003 if ( !$this->needsDB() ) {
2004 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2005 ' method should return true. Use @group Database or $this->tablesUsed.' );
2006 }
2007
2008 $db = wfGetDB( DB_REPLICA );
2009
2010 $res = $db->select(
2011 $table,
2012 $fields,
2013 $condition,
2014 wfGetCaller(),
2015 $options + [ 'ORDER BY' => $fields ],
2016 $join_conds
2017 );
2018 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2019
2020 $i = 0;
2021
2022 foreach ( $expectedRows as $expected ) {
2023 $r = $res->fetchRow();
2024 self::stripStringKeys( $r );
2025
2026 $i += 1;
2027 $this->assertNotEmpty( $r, "row #$i missing" );
2028
2029 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2030 }
2031
2032 $r = $res->fetchRow();
2033 self::stripStringKeys( $r );
2034
2035 $this->assertFalse( $r, "found extra row (after #$i)" );
2036 }
2037
2038 /**
2039 * Utility method taking an array of elements and wrapping
2040 * each element in its own array. Useful for data providers
2041 * that only return a single argument.
2042 *
2043 * @since 1.20
2044 *
2045 * @param array $elements
2046 *
2047 * @return array
2048 */
2049 protected function arrayWrap( array $elements ) {
2050 return array_map(
2051 function ( $element ) {
2052 return [ $element ];
2053 },
2054 $elements
2055 );
2056 }
2057
2058 /**
2059 * Assert that two arrays are equal. By default this means that both arrays need to hold
2060 * the same set of values. Using additional arguments, order and associated key can also
2061 * be set as relevant.
2062 *
2063 * @since 1.20
2064 *
2065 * @param array $expected
2066 * @param array $actual
2067 * @param bool $ordered If the order of the values should match
2068 * @param bool $named If the keys should match
2069 */
2070 protected function assertArrayEquals( array $expected, array $actual,
2071 $ordered = false, $named = false
2072 ) {
2073 if ( !$ordered ) {
2074 $this->objectAssociativeSort( $expected );
2075 $this->objectAssociativeSort( $actual );
2076 }
2077
2078 if ( !$named ) {
2079 $expected = array_values( $expected );
2080 $actual = array_values( $actual );
2081 }
2082
2083 call_user_func_array(
2084 [ $this, 'assertEquals' ],
2085 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2086 );
2087 }
2088
2089 /**
2090 * Put each HTML element on its own line and then equals() the results
2091 *
2092 * Use for nicely formatting of PHPUnit diff output when comparing very
2093 * simple HTML
2094 *
2095 * @since 1.20
2096 *
2097 * @param string $expected HTML on oneline
2098 * @param string $actual HTML on oneline
2099 * @param string $msg Optional message
2100 */
2101 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2102 $expected = str_replace( '>', ">\n", $expected );
2103 $actual = str_replace( '>', ">\n", $actual );
2104
2105 $this->assertEquals( $expected, $actual, $msg );
2106 }
2107
2108 /**
2109 * Does an associative sort that works for objects.
2110 *
2111 * @since 1.20
2112 *
2113 * @param array &$array
2114 */
2115 protected function objectAssociativeSort( array &$array ) {
2116 uasort(
2117 $array,
2118 function ( $a, $b ) {
2119 return serialize( $a ) <=> serialize( $b );
2120 }
2121 );
2122 }
2123
2124 /**
2125 * Utility function for eliminating all string keys from an array.
2126 * Useful to turn a database result row as returned by fetchRow() into
2127 * a pure indexed array.
2128 *
2129 * @since 1.20
2130 *
2131 * @param mixed &$r The array to remove string keys from.
2132 */
2133 protected static function stripStringKeys( &$r ) {
2134 if ( !is_array( $r ) ) {
2135 return;
2136 }
2137
2138 foreach ( $r as $k => $v ) {
2139 if ( is_string( $k ) ) {
2140 unset( $r[$k] );
2141 }
2142 }
2143 }
2144
2145 /**
2146 * Asserts that the provided variable is of the specified
2147 * internal type or equals the $value argument. This is useful
2148 * for testing return types of functions that return a certain
2149 * type or *value* when not set or on error.
2150 *
2151 * @since 1.20
2152 *
2153 * @param string $type
2154 * @param mixed $actual
2155 * @param mixed $value
2156 * @param string $message
2157 */
2158 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2159 if ( $actual === $value ) {
2160 $this->assertTrue( true, $message );
2161 } else {
2162 $this->assertType( $type, $actual, $message );
2163 }
2164 }
2165
2166 /**
2167 * Asserts the type of the provided value. This can be either
2168 * in internal type such as boolean or integer, or a class or
2169 * interface the value extends or implements.
2170 *
2171 * @since 1.20
2172 *
2173 * @param string $type
2174 * @param mixed $actual
2175 * @param string $message
2176 */
2177 protected function assertType( $type, $actual, $message = '' ) {
2178 if ( class_exists( $type ) || interface_exists( $type ) ) {
2179 $this->assertInstanceOf( $type, $actual, $message );
2180 } else {
2181 $this->assertInternalType( $type, $actual, $message );
2182 }
2183 }
2184
2185 /**
2186 * Returns true if the given namespace defaults to Wikitext
2187 * according to $wgNamespaceContentModels
2188 *
2189 * @param int $ns The namespace ID to check
2190 *
2191 * @return bool
2192 * @since 1.21
2193 */
2194 protected function isWikitextNS( $ns ) {
2195 global $wgNamespaceContentModels;
2196
2197 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2198 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
2199 }
2200
2201 return true;
2202 }
2203
2204 /**
2205 * Returns the ID of a namespace that defaults to Wikitext.
2206 *
2207 * @throws MWException If there is none.
2208 * @return int The ID of the wikitext Namespace
2209 * @since 1.21
2210 */
2211 protected function getDefaultWikitextNS() {
2212 global $wgNamespaceContentModels;
2213
2214 static $wikitextNS = null; // this is not going to change
2215 if ( $wikitextNS !== null ) {
2216 return $wikitextNS;
2217 }
2218
2219 // quickly short out on most common case:
2220 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
2221 return NS_MAIN;
2222 }
2223
2224 // NOTE: prefer content namespaces
2225 $namespaces = array_unique( array_merge(
2226 MWNamespace::getContentNamespaces(),
2227 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
2228 MWNamespace::getValidNamespaces()
2229 ) );
2230
2231 $namespaces = array_diff( $namespaces, [
2232 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
2233 ] );
2234
2235 $talk = array_filter( $namespaces, function ( $ns ) {
2236 return MWNamespace::isTalk( $ns );
2237 } );
2238
2239 // prefer non-talk pages
2240 $namespaces = array_diff( $namespaces, $talk );
2241 $namespaces = array_merge( $namespaces, $talk );
2242
2243 // check default content model of each namespace
2244 foreach ( $namespaces as $ns ) {
2245 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2246 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2247 ) {
2248 $wikitextNS = $ns;
2249
2250 return $wikitextNS;
2251 }
2252 }
2253
2254 // give up
2255 // @todo Inside a test, we could skip the test as incomplete.
2256 // But frequently, this is used in fixture setup.
2257 throw new MWException( "No namespace defaults to wikitext!" );
2258 }
2259
2260 /**
2261 * Check, if $wgDiff3 is set and ready to merge
2262 * Will mark the calling test as skipped, if not ready
2263 *
2264 * @since 1.21
2265 */
2266 protected function markTestSkippedIfNoDiff3() {
2267 global $wgDiff3;
2268
2269 # This check may also protect against code injection in
2270 # case of broken installations.
2271 Wikimedia\suppressWarnings();
2272 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2273 Wikimedia\restoreWarnings();
2274
2275 if ( !$haveDiff3 ) {
2276 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2277 }
2278 }
2279
2280 /**
2281 * Check if $extName is a loaded PHP extension, will skip the
2282 * test whenever it is not loaded.
2283 *
2284 * @since 1.21
2285 * @param string $extName
2286 * @return bool
2287 */
2288 protected function checkPHPExtension( $extName ) {
2289 $loaded = extension_loaded( $extName );
2290 if ( !$loaded ) {
2291 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2292 }
2293
2294 return $loaded;
2295 }
2296
2297 /**
2298 * Skip the test if using the specified database type
2299 *
2300 * @param string $type Database type
2301 * @since 1.32
2302 */
2303 protected function markTestSkippedIfDbType( $type ) {
2304 if ( $this->db->getType() === $type ) {
2305 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2306 }
2307 }
2308
2309 /**
2310 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2311 * @param string $buffer
2312 * @return string
2313 */
2314 public static function wfResetOutputBuffersBarrier( $buffer ) {
2315 return $buffer;
2316 }
2317
2318 /**
2319 * Create a temporary hook handler which will be reset by tearDown.
2320 * This replaces other handlers for the same hook.
2321 * @param string $hookName Hook name
2322 * @param mixed $handler Value suitable for a hook handler
2323 * @since 1.28
2324 */
2325 protected function setTemporaryHook( $hookName, $handler ) {
2326 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2327 }
2328
2329 /**
2330 * Check whether file contains given data.
2331 * @param string $fileName
2332 * @param string $actualData
2333 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2334 * and skip the test.
2335 * @param string $msg
2336 * @since 1.30
2337 */
2338 protected function assertFileContains(
2339 $fileName,
2340 $actualData,
2341 $createIfMissing = false,
2342 $msg = ''
2343 ) {
2344 if ( $createIfMissing ) {
2345 if ( !file_exists( $fileName ) ) {
2346 file_put_contents( $fileName, $actualData );
2347 $this->markTestSkipped( 'Data file $fileName does not exist' );
2348 }
2349 } else {
2350 self::assertFileExists( $fileName );
2351 }
2352 self::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2353 }
2354
2355 /**
2356 * Edits or creates a page/revision
2357 * @param string $pageName Page title
2358 * @param string $text Content of the page
2359 * @param string $summary Optional summary string for the revision
2360 * @param int $defaultNs Optional namespace id
2361 * @return array Array as returned by WikiPage::doEditContent()
2362 * @throws MWException If this test cases's needsDB() method doesn't return true.
2363 * Test cases can use "@group Database" to enable database test support,
2364 * or list the tables under testing in $this->tablesUsed, or override the
2365 * needsDB() method.
2366 */
2367 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
2368 if ( !$this->needsDB() ) {
2369 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2370 ' method should return true. Use @group Database or $this->tablesUsed.' );
2371 }
2372
2373 $title = Title::newFromText( $pageName, $defaultNs );
2374 $page = WikiPage::factory( $title );
2375
2376 return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
2377 }
2378
2379 /**
2380 * Revision-deletes a revision.
2381 *
2382 * @param Revision|int $rev Revision to delete
2383 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2384 * clear, -1 to leave alone. (All other values also clear the bit.)
2385 * @param string $comment Deletion comment
2386 */
2387 protected function revisionDelete(
2388 $rev, array $value = [ Revision::DELETED_TEXT => 1 ], $comment = ''
2389 ) {
2390 if ( is_int( $rev ) ) {
2391 $rev = Revision::newFromId( $rev );
2392 }
2393 RevisionDeleter::createList(
2394 'revision', RequestContext::getMain(), $rev->getTitle(), [ $rev->getId() ]
2395 )->setVisibility( [
2396 'value' => $value,
2397 'comment' => $comment,
2398 ] );
2399 }
2400 }